package com.zzl.study.sharding.aop;

import com.zzl.study.sharding.aop.annotation.HintInlineAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author: zhangzl
 * @date: 2022/7/16 12:19
 * @version: 1.0
 * @description: 自定义Hint分片AOP切面
 */
@Slf4j
@Aspect
@Component
public class HintInlineAspectj {

    @Around("@annotation(com.zzl.study.sharding.aop.annotation.HintInlineAlgorithm)")
    public void doAround(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        HintInlineAlgorithm annotation = methodSignature.getMethod().getAnnotation(HintInlineAlgorithm.class);
        HintManager hintManager = HintManager.getInstance();
        if (annotation.isTableStrategy()) {
            hintManager.addTableShardingValue(annotation.logicTable(), annotation.hintValue());
        } else {
            hintManager.addDatabaseShardingValue(annotation.logicTable(), annotation.hintValue());
        }
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("调用ShardingJDBC Hint分片算法出错!", throwable);
        } finally {
            hintManager.close();
        }
    }

}
